package com.zhiyou.app.shop.website.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.aspectj.apache.bcel.generic.Type;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zhiyou.app.shop.common.BaseAction;
import com.zhiyou.app.shop.common.util.ShopConstants;
import com.zhiyou.app.shop.website.dao.IDicItemDao;
import com.zhiyou.app.shop.website.dao.IUserInfoDao;
import com.zhiyou.app.shop.website.dao.pojo.DicItem;
import com.zhiyou.app.shop.website.dao.pojo.User;
import com.zhiyou.app.shop.website.dao.pojo.UserAccount;
import com.zhiyou.app.shop.website.service.IDicItemService;
import com.zhiyou.app.shop.website.service.IUserAccountService;
import com.zhiyou.app.shop.website.service.IUserInfoService;
import com.zhiyou.app.shop.website.service.IUserManagerService;
import com.zhiyou.app.shop.website.service.IUserStockService;
import com.zhiyou.app.shop.website.util.CEncryptor;
import com.zhiyou.app.shop.website.util.EncryptData;
import com.zhiyou.app.shop.website.util.ReadWriteFile;

public class AppRelationAction extends BaseAction {
	
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private IUserAccountService userAccountService;
	@Autowired
	private IUserManagerService userManagerService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IDicItemService dicItemService;
	@Autowired
	private IUserInfoDao userInfoDao;  
	@Autowired
	private IUserStockService userStockService;
	
	private String username;
	private String pwd;
	private String type;
	private String appType;
	
	public String doLogin(){
		JsonObject json = new JsonObject();
		
		try {
			PrintWriter out = getResponse().getWriter();
			if (username != null && pwd!= null) {
				User user = new User();
				user.setUserAccount(username);	
				if("ios".equals(appType)){
					if("1".equals(type)){					
						user.setFirstPwd(encodePassword(pwd));
					}else if("3".equals(type)){
						user.setThirdPwd(encodePassword(pwd));
					}else{
						user.setFirstPwd("");
						user.setThirdPwd("");
					}
				}else if("android".equals(appType)){
					if("1".equals(type)){					
						user.setFirstPwd(pwd);
					}else if("3".equals(type)){
						user.setThirdPwd(pwd);
					}else{
						user.setFirstPwd("");
						user.setThirdPwd("");
					}
				}else{
					user.setFirstPwd("");
					user.setThirdPwd("");
				}
				/*if("1".equals(type)){					
					user.setFirstPwd(encodePassword(pwd));
				}else if("3".equals(type)){
					user.setThirdPwd(pwd);
				}else{
					user.setFirstPwd("");
					user.setThirdPwd("");
				}*/
				user.setFlag(ShopConstants.TRUE);
				user.setActivity(ShopConstants.TRUE);
				// 根据用户名和密码获取用户列表
				List<User> list = userManagerService.login(user);
				if (list != null && list.size() > 0) {
					json.addProperty("loginFlag", 1);
					if("ios".equals(appType)){
						json.addProperty("firstPwdEcode", user.getFirstPwd());						
					}
				} else {
					json.addProperty("loginFlag", 0);
				}
			} else {
				json.addProperty("loginFlag", 0);
			}
			out.print(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			try {
				json.addProperty("loginFlag", 0);
				PrintWriter out = getResponse().getWriter();
				out.print(json);
				out.flush();
				out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		System.out.println(json);
		return null;
	}

	public String findVersion(){
		JsonObject json = new JsonObject();
		try {
			PrintWriter out = getResponse().getWriter();
			DicItem dicItem = dicItemService.findByTypeAndCode("app_version", "1");
			if(dicItem != null){
				//json.addProperty("result", "1");
				json.addProperty("version", dicItem.getName());
				json.addProperty("address", dicItem.getRemark());
			}else{
				//json.addProperty("result", "0");
				json.addProperty("version","");
				json.addProperty("address","");
			}
			out.print(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String sycUser(){
		try {
			PrintWriter out = getResponse().getWriter();
			//DicItem dicItem = dicItemService.findByTypeAndCode(ShopConstants.XMPP, "0");
			//"http://103.31.222.70/MobileAdmin/iface/user/registerjj.shtml";
			/*String xmppurl = "http://103.31.222.70/MobileAdmin/iface/user/registerjj.shtml";
			try {
				HttpPost post = new HttpPost(xmppurl);
				//添加参数
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("nickname", "serviceOSLT03"));
				params.add(new BasicNameValuePair("password", encodePassword("7070822053oslt")));
				params.add(new BasicNameValuePair("attr1", "1"));
				post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				//发送请求
				HttpClient http = new DefaultHttpClient();
				HttpResponse response = http.execute(post);
				HttpEntity entity = response.getEntity();
				System.out.println("Login form get: " + response.getStatusLine() + entity.getContent());
				System.out.println(response.getStatusLine().getStatusCode());
				if(response.getStatusLine().getStatusCode() == 200){
					String results = EntityUtils.toString(response.getEntity());
					Gson gson = new Gson();
					JsonArray array = new JsonArray();
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}*/
			List<User> list = userInfoService.findAll();
			if(list != null){
				for (User user : list) {
					DicItem dicItem = dicItemService.findByTypeAndCode(ShopConstants.XMPP, "0");
					//"http://103.31.222.70/MobileAdmin/iface/user/registerjj.shtml";
					//String xmppurl = "http://"+dicItem.getName()+"/MobileAdmin/iface/user/registerjj.shtml";
					String xmppurl = "http://localhost:8080/MobileAdmin/iface/user/registerjj.shtml";
					try {
						HttpPost post = new HttpPost(xmppurl);
						//添加参数
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("nickname", user.getUserAccount().toLowerCase()));
						params.add(new BasicNameValuePair("password", user.getFirstPwd()));
						params.add(new BasicNameValuePair("attr1", "1"));
						post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
						//发送请求
						HttpClient http = new DefaultHttpClient();
						HttpResponse response = http.execute(post);
						HttpEntity entity = response.getEntity();
						System.out.println("Login form get: " + response.getStatusLine() + entity.getContent());
						System.out.println(response.getStatusLine().getStatusCode());
						/*if(response.getStatusLine().getStatusCode() == 200){
							String results = EntityUtils.toString(response.getEntity());
							Gson gson = new Gson();
							JsonArray array = new JsonArray();
						}*/
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			out.print("同步完成");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	public String findChildByName(){
		//List<User> list = userInfoDao.findByProperty("recommendId", "cn842059");
		List<User> allChild = new ArrayList<User>();
		findUser(allChild,"cn842059");
		UserAccount account = null;
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			//ReadWriteFile.creatTxtFile();
			for (User user : allChild) {
				if(user.getActivityDate() != null){
					if(new Date(user.getActivityDate().getTime()).before(sdf.parse("2013-12-02 23:59:59"))){
						account = userAccountService.findByUserAccount(user.getUserAccount());
						if(account.getStockNum().longValue() == userStockService.findUserStock(user.getUserAccount(), "1")){
							System.out.println(account.getUserId()+"--"+user.getActivityDate()+"--"+account.getStockNum()+"--"+userStockService.findUserStock(user.getUserAccount(), "1"));
							userStockService.saveStockSome(user.getUserAccount());
						}
//						ReadWriteFile.readTxtFile();
//						ReadWriteFile.writeTxtFile(account.getUserId()+"--"+user.getActivityDate()+"--"+account.getStockNum()+"--"+userStockService.findUserStock(user.getUserAccount(), "1"));			
					}					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private List<User> findUser(List<User> list, String userAccount){
		List<User> childList =userInfoDao.findByRecommendId(userAccount);
				//userInfoDao.findByProperty("recommendId", userAccount);
		if(childList != null && childList.size() > 0){
			list.addAll(childList);
			for (User user : childList) {
				findUser(list, user.getUserAccount());
			}
		}
		return list;
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getAppType() {
		return appType;
	}

	public void setAppType(String appType) {
		this.appType = appType;
	}
	
}
